#!/bin/bash

set -e

dataMnt=/mnt/server.lan/data
dataStorage=$dataMnt/dataStorage

flag=false
if [ ! -e "$dataStorage" ];then
  echo "[E] $dataStorage : dir not exists,please make it"
  flag=true
fi

if [ -z "$TZ" ];then
  # "Asia/Shanghai"
  echo '[ERR] env TZ  not set, and install "tzdata" '
  flag=true
fi

if $flag;then
  exit 1
fi

###################
## settings
name="git.lan"

# gitea version v1.15.3 
# https://hub.docker.com/r/gitea/gitea
## arm64 x86 # amd64||arm64||aarch64 
image="gitea/gitea:1.15"
# armv7 armhf
if [ "`uname -m`" == "armv7l" ];then
  # image="inthbl/gitea-armhf:1.15"
  # inthbl/gitea-1.15-armhf
  image=inthbl/gitea-1.15-armhf
fi

docker pull "${image}"

mkDir() {
  if [ -z "$1" ]; then
    return
  fi

  if [ ! -e "${1}" ]; then
    mkdir -p "${1}"
    chown 1000:1000 "${1}"
  fi
}
dataDir="$dataStorage/$name"
mkDir "${dataDir}"

genMailer(){
  echo "[TODO] Mailer"
  # add or modify these lines

  # [mailer]
  # ENABLED = true
  # HOST    = smtp.qq.com:465
  # FROM    = "serverBot"<xxx@qq.com>
  # USER    = xxx@qq.com
  # PASSWD  = xxxxxx

}

if [ ! -e "$dataDir/gitea/conf/" ];then
  mkdir -p "$dataDir/gitea/conf/"
  tmpini="/tmp/__gitea_app.ini"
  cp "$(dirname "$0")/git_app.ini" "$tmpini"
  genMailer "$tmpini"
  cp "$tmpini" "$dataDir/gitea/conf/app.ini"
  chown -R 1000:1000 "${dataDir}"
fi


echo "[Warn] set sshd to another port .. eg. :22222"

docker run -d --name "${name}" \
    --restart=always \
    -e TZ=$TZ \
    -v /usr/share/zoneinfo/$TZ:/etc/localtime:ro \
    -v /etc/timezone:/etc/timezone:ro \
    -e USER_UID=1000 \
    -e USER_GID=1000 \
    -v "$dataDir":/data \
    -p 127.0.0.1:12222:22 \
    -p 127.0.0.1:3000:3000 \
    "${image}"

exit $?
